<?php

class TinyMceWidget extends CInputWidget
{    
    public $editorOptions = array();
    
    public $model;
    
    public $attribute;
    
    public function run()
    {
        list($name, $id) = $this->resolveNameID();
        
        // Registering javascript.
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('jquery');
        $cs->registerScriptFile('/assets/tiny_mce/jquery.tinymce.js');
        
        $defaultOptions = array(
            'script_url' => '/assets/tiny_mce/tiny_mce.js',
            'width'=> '100%',
            'height'=> '200px',
            'theme'=>'advanced',
            'language'=>'ru',
            'theme_advanced_toolbar_location'=>'top',
            'theme_advanced_toolbar_align'=>'left',
            'theme_advanced_statusbar_location'=>'bottom',
            'content_css'=>'/assets/tiny_mce/editor.css',
            'plugins'=>'autolink,lists,pagebreak,layer,table,advhr,advimage,advlink,iespell,inlinepopups,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist',
            'theme_advanced_buttons1'=>'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,nonbreaking',
            'theme_advanced_buttons2'=>'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,preview,|,forecolor,backcolor',
            'theme_advanced_buttons3'=>'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,fullscreen,|,pagebreak',
        );
        $this->editorOptions = array_merge($defaultOptions, $this->editorOptions);
        
        $cs->registerScript(
            'Yii.'.get_class($this).'#'.$id,
            '$(function(){$("#'.$id.'").tinymce('.CJavaScript::encode($this->editorOptions).');});'
        );
        
        $this->htmlOptions['id'] = $id;
        
        if($this->hasModel())
            $html = CHtml::activeTextArea($this->model, $this->attribute, $this->htmlOptions);
        else
            $html = CHtml::textArea($name, $this->value, $this->htmlOptions);
        $html .= Chtml::button('+ Картинку');
        $html .= Chtml::button('Выбрать файл/картинку', array('onclick'=>'__elfinderOpen();'));
        $html .= Chtml::button('Отключить редактор');
        echo $html;
    }
}
